#!/bin/sh

TAR="tar --sort=name --mtime=@1445385600 --owner=root --group=root --numeric-owner --mode=go=rX,u+rw,a-s -cvf"

dl_git() {
    repo="$1"
    project=$(basename "$repo")
    project="${project%.git}"
    commit="$2"
    expected_hash="$3"
    
    echo "DL: git download"
    echo "DL: - repo: $repo"
    echo "DL: - project: $project"
    echo "DL: - commit: $commit"
    
    git clone "$repo" || exit -1
    cd "$project"
    git checkout "$commit" || exit -1
    yes | rm -r .git
    cd ..
    
    $TAR "$project".tar "$project" > /dev/null
    
    hash=$(sha256sum "$project".tar | cut -b -64)
    
    echo "DL: - hash: $hash"
    if [ "$hash" = "$expected_hash" ]; then
        echo "DL: hash validated!"
    else
        echo "DL: ERROR hash validation failed!"
        echo "DL: ERROR got $expected_hash"
        exit -1
    fi

    mv "$project".tar "../dump/$hash".tar
}

dl_wget() {
    project="$1"
    link="$2"
    expected_hash="$3"
    
    echo "DL: wget download"
    echo "DL: - project: $project"
    echo "DL: - link: $link"
    
    wget --no-check-certificate "$link" || exit -1
    tar -xvf $(basename "$link") --no-same-owner > /dev/null || exit -1
    $TAR "$project".tar "$project" > /dev/null || exit -1
    
    hash=$(sha256sum "$project".tar | cut -b -64)
    
    echo "DL: - hash: $hash"
    if [ "$hash" = "$expected_hash" ]; then
        echo "DL: hash validated!"
    else
        echo "DL: ERROR hash validation failed!"
        echo "DL: ERROR got $expected_hash"
        exit -1
    fi
    
    mv "$project".tar "../dump/$hash".tar
}

. ./pkg.sh

mkdir -p dump

mkdir -p upstream
cd upstream

# dl_git git://git.musl-libc.org/musl \
#        5978eb703ce0e64dd778a88c1ffffb76fe5e2202 \
#        "$MUSL_HASH"

# dl_git git://git.suckless.org/sbase \
#        4093341657c67f03b48718647b2cd378e74c14dc \
#        "$SBASE_HASH"

# dl_git git://git.suckless.org/ubase \
#        e0dc3f9546b3cd839aef8e58376c6295679a5ed5 \
#        "$UBASE_HASH"

# dl_git git://git.suckless.org/sinit \
#        40a9fd323646b680a4eb046076c606339fd7501e \
#        "$SINIT_HASH"

# dl_git git://git.suckless.org/smdev \
#        8d07540c417e3a31942028318197c89b640278d5 \
#        "$SMDEV_HASH"

dl_wget mksh \
        https://www.mirbsd.org/MirOS/dist/mir/mksh/mksh-R52c.tgz \
        "$MKSH_HASH"

dl_wget module-init-tools-3.15 \
        https://www.kernel.org/pub/linux/utils/kernel/module-init-tools/module-init-tools-3.15.tar.gz \
        "$MODTOOLS_HASH"

dl_git http://repo.or.cz/fbvis.git \
       58caabc93604a586f8470f0f2274270182bc643d \
       "$FBVIS_HASH"

# dl_wget fbset-2.1 \
#         http://users.telenet.be/geertu/Linux/fbdev/fbset-2.1.tar.gz \
#         "$FBSET_HASH"
